<template>
  <a-modal v-model:visible="visible" title="创建资讯文章" :width="1200" :footer="false">
    <a-row>
      <a-form ref="formRef" :model="form" size="medium" auto-label-width :style="{ width: 'auto' }">
        <a-form-item style="width: 370px" field="name" label="任务名称" :rules="rules.name">
          <a-input v-model="form.name" placeholder="请输入" />
        </a-form-item>
        <a-form-item style="width: 370px" field="template_id" label="选择模板" :rules="rules.template_id">
          <a-select
            ref="templateSelectRef"
            allow-search
            @dropdown-reach-bottom="getTemplateData()"
            :loading="loadingTemp"
            @search="handleSearch"
            v-model="form.template_id"
            placeholder="请选择类型"
            allow-clear
            @change="handleChangeTemplate"
          >
            <a-option v-for="item in templateOption" :value="item.id">{{ item.name }}({{ item.type_text }})</a-option>
          </a-select>
          <icon-bar-chart style="cursor: pointer; margin-left: 8px" size="18" @click="() => chartModalRef.show()" />
        </a-form-item>
        <a-form-item style="width: 370px" field="push_system_id" label="推送平台" :rules="rules.push_system_id">
          <a-cascader :options="pushSystemOptions" v-model="form.push_system_id" placeholder="请选择" allow-clear />
        </a-form-item>
        <!-- <a-form-item style="width: 370px" field="number" label="生成数量" :rules="rules.number">
          <a-input-number v-model="form.number" placeholder="请输入数字字符" />
        </a-form-item> -->
        <!-- <a-form-item field="time" label="生成时间" :rules="rules.time">
          <a-space>
            <a-date-picker
              v-model="form.time"
              style="width: 194px"
              placeholder="请选择生成时间"
              show-time
              :time-picker-props="{ defaultValue: '09:00:00' }"
              format="YYYY-MM-DD HH:mm:ss"
            />
            <a-checkbox v-model="form.repeat_type" style="white-space: nowrap">重复</a-checkbox>
            <a-select
              v-if="form.repeat_type"
              v-model="form.date"
              :style="{ width: '200px' }"
              placeholder="请选择重复类型"
            >
              <a-option value="0">每天</a-option>
              <a-option value="1">周一</a-option>
              <a-option value="2">周二</a-option>
              <a-option value="3">周三</a-option>
              <a-option value="4">周四</a-option>
              <a-option value="5">周五</a-option>
              <a-option value="6">周六</a-option>
              <a-option value="7">周天</a-option>
            </a-select>
          </a-space>
        </a-form-item> -->
      </a-form>
    </a-row>
    <a-space style="margin-left: 84px">
      <a-button type="primary" @click="handleSubmit">
        <template #default>确认生成</template>
      </a-button>
    </a-space>
    <!-- 表格 -->
    <a-table
      style="margin-top: 20px; max-height: 300px"
      row-key="id"
      size="small"
      :bordered="{ cell: true }"
      :loading="loading"
      :data="tableData"
      :scroll="{ x: '100%', y: '280px', minWidth: 1000 }"
      :pagination="{ showPageSize: true, showTotal: true, total: total, current: current, pageSize: pageSize }"
      @page-change="changeCurrent"
      @page-size-change="changePageSize"
    >
      <template #columns>
        <a-table-column title="任务名称" data-index="name"></a-table-column>
        <a-table-column title="模板名称">
          <template #cell="{ record }">
            {{ record.template_one.name || '' }}
          </template>
        </a-table-column>
        <a-table-column title="推送栏目">
          <template #cell="{ record }">
            {{ record.push_system_one.name || '' }}
            {{ record.system_channel_one ? `/${record.system_channel_one.name}` : '' }}
          </template>
        </a-table-column>
        <!-- <a-table-column title="目标数量" data-index="number"></a-table-column> -->
        <!-- <a-table-column title="生成时间" :width="200" data-index="time_text"> </a-table-column> -->
        <a-table-column title="状态" data-index="status">
          <template #cell="{ record }">
            <a-tag v-if="record.status == '-1'">{{ statusMap[record.status] }}</a-tag>
            <a-tag v-if="record.status == '0'" color="blue">{{ statusMap[record.status] }}</a-tag>
            <a-tag v-if="record.status == '1'" color="orange">{{ statusMap[record.status] }}</a-tag>
            <a-tag v-if="record.status == '2'" color="green">{{ statusMap[record.status] }}</a-tag>
          </template>
        </a-table-column>
        <a-table-column title="操作" :width="180">
          <template #cell="{ record }">
            <a-space v-if="record.status != '2'">
              <a-popconfirm content="确认删除?" @ok="handleDelete(record)">
                <a-link status="danger">
                  <template #default>删除</template>
                </a-link>
              </a-popconfirm>
              <a-popconfirm v-if="record.status == '-1'" content="确认启用?" @ok="handleChangeStatus(record, 0)">
                <a-link>
                  <template #default>启用</template>
                </a-link>
              </a-popconfirm>
              <a-popconfirm v-if="record.status == '0'" content="确认停止?" @ok="handleChangeStatus(record, -1)">
                <a-link>
                  <template #default>停止</template>
                </a-link>
              </a-popconfirm>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>
  </a-modal>
  <chartModal :tabList="statusOption" ref="chartModalRef"></chartModal>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { Message, Modal, type FormInstance } from '@arco-design/web-vue'
import { IconEdit, IconPlus } from '@arco-design/web-vue/es/icon'
import { getTemplateList, getTaskList, addTaskList, changeTaskStatus, deleteTaskList, getTemplateDetail } from '@/apis'
import chartModal from '@/views/template-management/chartModal.vue'
import { usePagination } from '@/hooks'
import { format } from 'date-fns'

const templateSelectRef = ref(null)
const chartModalRef = ref(null)
const props = defineProps({
  pushSystemOptions: {
    type: Array,
    default: () => []
  },
  system_channel: {
    type: Array,
    default: () => []
  }
})
type Form = { name: string; url: string; id?: string }
const form: Form = reactive({
  name: '',
  template_id: '',
  push_system_id: '',
  number: 1,
  repeat_type: false,
  date: '0',
  time: ''
})
const statusMap = {
  '-1': '已暂停',
  '0': '未开始',
  '1': '进行中',
  '2': '已完成'
}
const rules = {
  name: [{ required: true, message: '请输入任务名称' }],
  template_id: [{ required: true, message: '请选择模板' }],
  push_system_id: [{ required: true, message: '请选择推送平台' }],
  number: [{ required: true, message: '请输入生成数量' }],
  time: [{ required: true, message: '请选择生成时间' }]
}

const templatepager = reactive({
  page: 1,
  pageSize: 100,
  total: 0
})
const templateOption = ref([])
const loadingTemp = ref(false)
// 获取模板下拉
const getTemplateData = async (query?: string) => {
  loadingTemp.value = true
  const res = await getTemplateList({
    status: 1,
    keyword: query || '',
    page: templatepager.page,
    pagesize: templatepager.pageSize
  }).then((res) => {
    if (res.code == 1) {
      if (res.data.data?.length > 0) {
        templateOption.value = templateOption.value.concat(res.data.data || [])
        templatepager.page++
      }
    } else {
    }
    loadingTemp.value = false
  })
}
getTemplateData()

// 搜索
const handleSearch = (val) => {
  templatepager.page = 1
  templateOption.value = []
  getTemplateData(val)
}

const emits = defineEmits(['reFreshTable'])
const visible = ref(false)
const detailId = ref('')
const formRef = ref<FormInstance>()

// 任务表格
const { current, pageSize, total, changeCurrent, changePageSize, setTotal } = usePagination(() => initTaskList())

const tableData = ref([])
const initTaskList = async () => {
  let res = await getTaskList({ page: current.value, pagesize: pageSize.value })
  tableData.value = res.data?.data || []
  setTotal(res.data?.total || 0)
}
const show = (id: string) => {
  visible.value = true
  initTaskList()
}
function findNodeById(nodes, id) {
  // 遍历所有根节点
  for (let node of nodes) {
    const result = findNodeInTree(node, id)
    if (result) {
      return result
    }
  }
  // 如果没有找到匹配的节点，返回 null
  return null
}

function findNodeInTree(node, id) {
  // 如果当前节点的 ID 匹配，返回当前节点
  if (node.id === id) {
    return node
  }

  // 如果当前节点有子节点，则递归查找每个子节点
  if (node.child) {
    for (let child of node.child) {
      const result = findNodeInTree(child, id)
      if (result) {
        return result
      }
    }
  }

  // 如果没有找到匹配的节点，返回 null
  return null
}
// 生成任务
const handleSubmit = async () => {
  const flag = await formRef.value?.validate()
  if (flag) {
    return false
  }
  let params = {
    template_id: form.template_id,
    name: form.name,
    number: '0',
    time: '0',
    repeat_type: '0'
  }
  let curTreeDate = findNodeById(props.system_channel, form.push_system_id)
  params.push_system_id = curTreeDate.push_system_id
  params.system_channel_id = form.push_system_id
  // 判断时间显示格式
  // if (form.repeat_type) {
  //   if (form.date == 0) {
  //     params.date = null
  //     params.repeat_type = 1
  //   } else {
  //     params.date = form.date
  //     params.repeat_type = 2
  //   }
  // } else {
  //   params.repeat_type = 0
  //   params.date = format(new Date(form.time), 'yyyy-MM-dd')
  // }

  let res = await addTaskList(params)
  if (res.code == 1) {
    Message.success(res.msg || '生成成功')
    form.name = ''
    form.template_id = ''
    form.push_system_id = ''
    form.number = 1
    form.repeat_type = false
    form.date = '0'
    form.time = ''
    initTaskList()
  } else {
    Message.error(res.msg || '生成失败')
  }
}
const handleChangeStatus = async (record, status) => {
  let res = await changeTaskStatus({
    task_id: record.id,
    status
  })
  if (res.code == 1) {
    Message.success(res.msg || '操作成功')
    initTaskList()
  } else {
    Message.error(res.msg || '操作失败')
  }
}
// 删除任务
const handleDelete = async (record) => {
  let res = await deleteTaskList({ task_id: record.id })
  if (res.code == 1) {
    Message.success(res.msg || '删除成功')
    initTaskList()
  } else {
    Message.error(res.msg || '删除失败')
  }
}
// 选择模板自动填充推送栏目
const handleChangeTemplate = async (val) => {
  let res = await getTemplateDetail({
    template_id: val
  })
  if (res.code == 1) {
    // form.push_system_id = [res.data?.push_system, res.data?.system_id, res.data?.system_channel_id]
    form.push_system_id = res.data?.system_channel_id
  } else {
    Message.error(res.msg || '获取模板失败')
  }
}
defineExpose({ show })
</script>

<style lang="scss" scoped>
:deep(.arco-collapse-item-content) {
  background: none;
}
</style>
